package com.example.applets.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.applets.entity.Role;
import com.example.applets.service.impl.RoleServiceImpl;
import com.example.applets.util.AjaxResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 角色表 前端控制器
 * </p>
 *
 * @author 云烟成雨丶
 * @since 2020-10-09
 */
@Controller
@RequestMapping("/applets/role")
public class RoleController {
    @Autowired
    private RoleServiceImpl roleService;

    @RequestMapping("/page")
    @ResponseBody
    public AjaxResult selectPage(@RequestParam("rolename") String rolename, @RequestParam(value = "pageNo", defaultValue = "1") int pageNo, @RequestParam(value = "pageSize", defaultValue = "5") int pageSize) {
        //分页
        Page<Role> page = new Page<>(pageNo, pageSize);
        QueryWrapper<Role> wrapper = new QueryWrapper<>();
        //条件构造器
        if (!rolename.equals(""))
            wrapper.like("rolename", rolename);
        //获得集合
        List<Role> list = roleService.page(page, wrapper).getRecords();
        //获得页数
        int count = (roleService.count(wrapper) - 1) / pageSize + 1;
        //创建map集合
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("list", list);
        map.put("total", count);
        if (list.size() == 0)
            return AjaxResult.error("暂无数据");
        return AjaxResult.success(map);
    }

    @RequestMapping("/delete")
    @ResponseBody
    //修改用户
    public AjaxResult deleteRole(@RequestParam("id") long id) {
        Role role = roleService.getById(id);
        role.setInuse(false);
        if (!roleService.updateById(role))
            return AjaxResult.error("删除失败!");
        return AjaxResult.success("删除成功!");
    }

    @RequestMapping("/select")
    //查找单个
    public String selectRole(@RequestParam("id") Long id, Model model) {
        Role role = roleService.getById(id);
        model.addAttribute("r", role);
        return "KRole/UpdateRole";
    }

    @RequestMapping("/update")
    @ResponseBody
    //修改用户
    public AjaxResult updateRole(Role role) {
        if (!roleService.updateById(role))
            return AjaxResult.error("修改失败!");
        return AjaxResult.success("修改成功!");
    }

    @RequestMapping("/add")
    @ResponseBody
    //修改用户
    public AjaxResult addRole(Role role) {
        if (!roleService.save(role))
            return AjaxResult.error("增加失败!");
        return AjaxResult.success("增加成功!");
    }
}

